const express = require('express');
const { MongoClient, ObjectId } = require('mongodb');
const multer = require('multer');
const sharp = require('sharp');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const bodyParser = require('body-parser');

function generateHash(filePath) {
    const fileData = fs.readFileSync(filePath);
    const hash = crypto.createHash('md5').update(fileData).digest('hex');
    return hash;  // 您可以根据实际需求更改文件扩展名
}

const app = express();
app.use(bodyParser.json()); // 用于解析JSON格式的请求体

const port = 4200;
// const IMAGE_PATH = '/root/apps/mongo-pic/public/'
const IMAGE_PATH = '/root/www/pic/'

// 连接MongoDB数据库
// const mongoUrl = 'mongodb://admin:jsz04005301@42.194.197.253:27017';
const mongoUrl = "mongodb://books:jsz04005301@42.194.197.253:27017/books";

const dbName = 'image-gallery';

MongoClient.connect(mongoUrl, (err, client) => {
    if (err) throw err;
    const db = client.db(dbName);

    // 定义图片集合
    const imageCollection = db.collection('images');

    // 定义标签集合
    const tagCollection = db.collection('tags');

    // 配置Multer存储设置
    const storage = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, IMAGE_PATH);
        },
        // filename: (req, file, cb) => {
        //     cb(null, `${Date.now()}-${file.originalname}`);
        // },
        // filename: (req, file, cb) => {
        //     console.log("buffer ---", file.buffer)
        //     const hash = generateHash(file.path);
        //     cb(null, `${hash}.${path.extname(file.originalname)}`);
        // },
    });
    const upload = multer({ storage });

    // app.use('/mps/res', express.static(IMAGE_PATH));


    app.get('/mps/img.html', (req, res) => {
        res.sendFile(path.join(__dirname, 'img.html'));
    });

    app.get('/mps/tag.html', (req, res) => {
        res.sendFile(path.join(__dirname, 'tag.html'));
    });
    

    // 处理图片上传
    app.post('/mps/upload', upload.single('image'), async (req, res) => {
        try {
            const { name, type } = req.body;
            const file = req.file;
            // console.log({ name, type }, "file.filePath", file)

            const fname = generateHash(file.path) + ".jpg";
            const fpath = path.join(IMAGE_PATH, fname)
            fs.renameSync(file.path, fpath);

            const thumbnailName = fname.replace(/\.(jpg|jpeg|png)$/, ".min.$1");

            // 生成缩略图
            const thumbnailPath = path.join(IMAGE_PATH, thumbnailName);

            const metadata = await sharp(fpath).metadata();
            // console.log("metadata", metadata)
            await sharp(fpath)
                .resize(300, 300, {
                    fit: 'inside',
                    withoutEnlargement: true,
                })
                .toFile(thumbnailPath);

            // 保存图片信息到数据库
            const imageInfo = {
                name: fname,
                width: metadata.width,
                height: metadata.height,
                size: Math.round(file.size / 1024), // Unit is KB
                tags: [],
                thumbnail: thumbnailName,
            };
            await imageCollection.insertOne(imageInfo);

            res.status(200).json({ message: 'Image uploaded successfully' });
        } catch (err) {
            console.error(err);
            res.status(500).json({ message: 'Error uploading image' });
        }
    });

    // 根据标签检索图片
    app.get('/mps/by-tag/:tagId', async (req, res) => {
        // 其他代码保持不变
    });

    app.get('/mps/images', async (req, res) => {
        try {
            const { page = 1, limit = 10 } = req.query;
            const skip = (page - 1) * limit;

            const total = await imageCollection.countDocuments({});
            const images = await imageCollection
                .find({})
                .skip(skip)
                .limit(limit)
                .toArray();

            res.json({
                data: images,
                total,
                page: parseInt(page),
                limit: parseInt(limit),
            });
        } catch (err) {
            console.error(err);
            res.status(500).json({ message: 'Error retrieving images' });
        }
    });

    // Delete image endpoint
    app.delete('/mps/images/:id', async (req, res) => {
        try {
            const { id } = req.params;
    
            // 在删除数据库记录之前先获取文件名
            const imageDoc = await imageCollection.findOne({ _id: new ObjectId(id) });
            if (!imageDoc) {
                return res.status(404).json({ message: 'Image not found' });
            }
            // console.log("doc------", imageDoc)
            // const imageFilename = imageDoc.filename;
            // const thumbnailFilename = `thumbnail_${imageFilename}`;
    
            // 执行删除操作
            const result = await imageCollection.deleteOne({ _id: new ObjectId(id) });
            if (result.deletedCount === 1) {
                // 删除文件系统上的图片和缩略图
                fs.unlinkSync(path.join(IMAGE_PATH, imageDoc.name));
                fs.unlinkSync(path.join(IMAGE_PATH, imageDoc.thumbnail));
    
                res.json({ message: 'Image and thumbnail deleted successfully' });
            } else {
                res.status(404).json({ message: 'Image not found' });
            }
        } catch (err) {
            console.error(err);
            res.status(500).json({ message: 'Error deleting image and thumbnail' });
        }
    });

    // 新建标签
    app.post('/mps/tags', async (req, res) => {
        try {
            console.log("req.body", req.body)
            const result = await tagCollection.insertOne(req.body);
            res.status(201).json({ message: 'Tag created successfully', tagId: result.insertedId });
        } catch (err) {
            console.log(err)
            res.status(500).json({ message: 'Error creating tag', err });
        }
    });

    // 编辑标签
    app.put('/mps/tags/:id', async (req, res) => {
        try {
            const result = await tagCollection.updateOne({ _id: new ObjectId(req.params.id) }, { $set: req.body });
            res.json({ message: 'Tag updated successfully' });
        } catch (err) {
            res.status(500).json({ message: 'Error updating tag' });
        }
    });

    // 查看标签列表
    app.get('/mps/tags', async (req, res) => {
        try {
            const tags = await tagCollection.find().toArray();
            res.json(tags);
        } catch (err) {
            res.status(500).json({ message: 'Error fetching tags' });
        }
    });

    // 查看特定标签
    app.get('/mps/tags/:id', async (req, res) => {
        try {
            const tag = await tagCollection.findOne({ _id: new ObjectId(req.params.id) });
            if (!tag) {
                return res.status(404).json({ message: 'Tag not found' });
            }
            res.json(tag);
        } catch (err) {
            res.status(500).json({ message: 'Error fetching tag' });
        }
    });

    // 删除标签
    app.delete('/mps/tags/:id', async (req, res) => {
        try {
            const result = await tagCollection.deleteOne({ _id: new ObjectId(req.params.id) });
            if (result.deletedCount === 0) {
                return res.status(404).json({ message: 'Tag not found' });
            }
            res.json({ message: 'Tag deleted successfully' });
        } catch (err) {
            res.status(500).json({ message: 'Error deleting tag' });
        }
    });

    app.listen(port, () => {
        console.log(`Server is running on port ${port}`);
    });
});